package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.bean.TradePaymentWindowBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.AtguiguUtil;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Objects;

/**
 * @Author lzc
 * @Date 2022/5/9 10:43
 */
public class Dws_08_DwsTradePaymentSucWindowApp extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_08_DwsTradePaymentSucWindowApp().init(
            "Dws_8_DwsTradePaymentSucWindowApp",
            4008,
            1,
            "Dws_8_DwsTradePaymentSucWindowApp",
            "Dws_8_DwsTradePaymentSucWindowApp",
            "dwd_trade_pay_detail_suc"
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 1. 由于dwd_trade_pay_detail_suc 有做连接, 所以数据中可能会有null, 需要先过滤掉null值.  注意需要修改kafkasource工具类
        SingleOutputStreamOperator<JSONObject> filteredStream = filterNullAndParse(stream);
        //        filteredStream.print("xxxx");
        // 2. 由于有left join, 所以可能会有重复数据, 需要按照order_detail_id实现去重, 思路同上
        SingleOutputStreamOperator<JSONObject> distinctedStream = distinctByOrderId(filteredStream);
        
        // 3. 独立支付人数和新增支付人数
        SingleOutputStreamOperator<TradePaymentWindowBean> tpwBeanStream = parseToTradePaymentWindowBean(distinctedStream);
        // 4. 开窗聚合
        SingleOutputStreamOperator<TradePaymentWindowBean> resultStream = windowAndAgg(tpwBeanStream);
        // 5. 写出到clickhouse中
        writeToClickhouse(resultStream);
        
        
    }
    
    private void writeToClickhouse(SingleOutputStreamOperator<TradePaymentWindowBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink(Constant.CLICKHOUSE_DB, "dws_trade_payment_suc_window", TradePaymentWindowBean.class));
    }
    
    private SingleOutputStreamOperator<TradePaymentWindowBean> windowAndAgg(
        SingleOutputStreamOperator<TradePaymentWindowBean> tpwBeanStream) {
        return tpwBeanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradePaymentWindowBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((tpw, ts) -> tpw.getTs())
            )
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
            .reduce(
                new ReduceFunction<TradePaymentWindowBean>() {
                    @Override
                    public TradePaymentWindowBean reduce(TradePaymentWindowBean tpw1,
                                                         TradePaymentWindowBean tpw2) throws Exception {
                        tpw1.setPaymentSucUniqueUserCount(tpw1.getPaymentSucUniqueUserCount() + tpw2.getPaymentSucUniqueUserCount());
                        tpw1.setPaymentSucNewUserCount(tpw1.getPaymentSucNewUserCount() + tpw2.getPaymentSucNewUserCount());
                        return tpw1;
                    }
                },
                new AllWindowFunction<TradePaymentWindowBean, TradePaymentWindowBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window,
                                      Iterable<TradePaymentWindowBean> values,
                                      Collector<TradePaymentWindowBean> out) throws Exception {
                        TradePaymentWindowBean bean = values.iterator().next();
                        
                        
                        bean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                        bean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        
                        bean.setTs(System.currentTimeMillis());
                        
                        
                        out.collect(bean);
                        
                        
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TradePaymentWindowBean> parseToTradePaymentWindowBean(
        SingleOutputStreamOperator<JSONObject> distinctedStream) {
        return distinctedStream
            .keyBy(obj -> obj.getString("user_id"))
            .process(new KeyedProcessFunction<String, JSONObject, TradePaymentWindowBean>() {
                
                private ValueState<String> lastPayDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastPayDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastPayDateState", String.class));
                }
                
                @Override
                public void processElement(JSONObject value,
                                           Context ctx,
                                           Collector<TradePaymentWindowBean> out) throws Exception {
                    
                    String date = DateFormatUtil.toDate(value.getLong("ts") * 1000);
                    String lastPayDate = lastPayDateState.value();
                    
                    TradePaymentWindowBean bean = new TradePaymentWindowBean();
                    bean.setTs(value.getLong("ts") * 1000);
                    if (lastPayDate == null) {
                        bean.setPaymentSucUniqueUserCount(1L);
                        bean.setPaymentSucNewUserCount(1L);
                        
                        out.collect(bean);
                        
                        lastPayDateState.update(date);
                        
                    } else {
                        if (!date.equals(lastPayDate)) {
                            bean.setPaymentSucUniqueUserCount(1L);
                            out.collect(bean);
                            lastPayDateState.update(date);
                        }
                    }
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> distinctByOrderId(SingleOutputStreamOperator<JSONObject> stream) {
        /*
            由于前面(预处理表)左连接的存在, 同一个order_detail_id会有多条数据, 要保留数据最全的那条记录
            
        时间最晚的数据最全
         row_op_ts 表示数据的生成时间  2022-05-08 15:30:56.723Z   row_op_ts":"2022-05-08 15:30:56.72Z
         */
        return stream
            .keyBy(obj -> obj.getLong("order_detail_id"))
            .process(new KeyedProcessFunction<Long, JSONObject, JSONObject>() {
                // 存储数据最全的状态
                private ValueState<JSONObject> lastDataState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastDataState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("lastDataState", JSONObject.class));
                }
                
                @Override
                public void processElement(JSONObject data,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject lastData = lastDataState.value();
                    if (lastData == null) {
                        // 把数据存入到状态中, 并定义定时器
                        lastDataState.update(data);
                        
                        ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000);
                    } else {
                        // 2022-05-08 15:30:56.723Z   row_op_ts":"2022-05-08 15:30:56.72Z
                        String currentTime = data.getString("row_op_ts");
                        String lastTime = lastData.getString("row_op_ts");
                        // 新数据的生成时间是否 大于 状态中的数据的生成时间
                        boolean isGreatOrEqual = AtguiguUtil.compareLTZ(currentTime, lastTime);
                        if (isGreatOrEqual) {
                            // 更新状态
                            lastDataState.update(data);
                        }
                    }
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<JSONObject> out) throws Exception {
                    out.collect(lastDataState.value());
                }
            });
    }
    
    private SingleOutputStreamOperator<JSONObject> filterNullAndParse(DataStreamSource<String> stream) {
        return stream
            .filter(Objects::nonNull)
            .map(JSON::parseObject);
        
    }
}
